package com.mdnote.structure.treebaswe;

import java.util.Arrays;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/29 
 * @description 顺序存储二叉树【数组 -> 二叉树遍历】
 */
public class ArrayToBinaryTree {

    /**
     * 节点
     */
    private static class Node {
        private int value;
        private Node left;
        private Node right;

        public Node(int value) {
            this.value = value;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public void setRight(Node right) {
            this.right = right;
        }
    }


    private int[] array;

    public ArrayToBinaryTree(int[] array) {
        this.array = array;
    }

    private void preOrder(int index) {
        if (this.array.length == 0) {
            throw new RuntimeException("数组不能为空");
        }

        System.out.print(array[index] + " ");
        if (2 * index + 1 < this.array.length) {
            preOrder(2 * index + 1);
        }
        if (2 * index + 2 < this.array.length) {
            preOrder(2 * index + 2);
        }
    }
    private void infixOrder(int index) {
        if (this.array.length == 0) {
            throw new RuntimeException("数组不能为空");
        }

        if (2 * index + 1 < this.array.length) {
            infixOrder(2 * index + 1);
        }
        System.out.print(array[index] + " ");
        if (2 * index + 2 < this.array.length) {
            infixOrder(2 * index + 2);
        }
    }

    private void postOrder(int index) {
        if (this.array.length == 0) {
            throw new RuntimeException("数组不能为空");
        }

        if (2 * index + 1 < this.array.length) {
            postOrder(2 * index + 1);
        }
        System.out.print(array[index] + " ");
        if (2 * index + 2 < this.array.length) {
            postOrder(2 * index + 2);
        }
    }


    public static void main(String[] args) {
        int[] array = {11, 22, 33, 44, 55};
        ArrayToBinaryTree arrayToBinaryTree = new ArrayToBinaryTree(array);
        System.out.println("转换前");
        System.out.println(Arrays.toString(array));
        System.out.println("转皇后");
        arrayToBinaryTree.preOrder(0);
    }
}
